<?php

class Answer
{
  private $value = false; // useful for loading answer from db when the school try to reanswer
  
  public function setValue($value)
  {
    $this->value = $value;
  }
  
  public function loadByCode($code)
  {
    $row = Db::fetchRow("SELECT * FROM answers WHERE answer_code = '$code'");
    if(empty($row))
    {
      throw new Exception('Bad answer code ' . $code);
    }
    foreach($row as $key=>$value)
    {
      $this->$key = $value;
    }
    return $this;
  }
  
  public function render()
  {
    $html = '';
    if($this->radio)
    {
      $html .= '<input type="radio" name="'.$this->answer_code.'" id="answer-'.$this->answer_id.'" ';
        if($this->value)
        {
          $html .= 'checked="checked" ';
        }
        $html .= '/>';
        $html .= '<label for="answer-'.$this->answer_id.'">'.$this->answer_string.'</label><br/>';
    }
    else
    {
      if($this->answer_need_specify)
      {
        $html .= '<input type="checkbox" name="'.$this->answer_code.'_switcher" id="answer-'.$this->answer_id.'" class="other_switcher" ';
        if($this->value)
        {
          $html .= 'checked="checked" ';
        }
        $html .= '/>';
        $html .= '<label for="answer-'.$this->answer_id.'" class="other_switcher">'.$this->answer_string.'</label></br>';
        $html .= '<input type="text" maxlength="500" size="50" class="other" name="'.$this->answer_code.'" id="'.$this->answer_code.'_switcher"';
        if($this->value)
        {
          $html .= 'value="'.$this->value.'" style="display:inline-block;" ';
        }
        $html .= ' /><br/>';
      }
      else
      {
        $html .= '<input type="checkbox" name="'.$this->answer_code.'" id="answer-'.$this->answer_id.'" ';
        if($this->value)
        {
          $html .= 'checked="checked" ';
        }
        $html .= '/>';
        $html .= '<label for="answer-'.$this->answer_id.'">'.$this->answer_string.'</label><br/>';
      }
    }
    return $html;
  }
}
